package com.fengmang.myapplication;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.smartapp.update.BatchUtils;
import com.smartapp.update.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

//import com.vondear.rxtools.RxAppTool;
//import com.vondear.rxtools.RxFileTool;

public class SplashActivity extends Activity {

	static {
		System.loadLibrary("SmartAppUpdate");
	}

	Context context;

	// 合成成功
	private static final int SUCCESS = 1;
	// 合成的APK签名和已安装的签名不一致
	private static final int FAIL_SING = -1;
	// 合成失败
	private static final int FAIL_ERROR = -2;
	// 获取源文件失败
	private static final int FAIL_GET_SOURCE = -3;
	public static final String PATH = Environment.getExternalStorageDirectory() + File.separator;
	public static final String NEW_APK_PATH = PATH + "new.apk";
	//	public static final String NEW_APK_PATH = PATH + "bsdiff_old.apk";
	public static final String PATCH_PATH = PATH + "myhotfix.patch";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		context = this;


		init();


	}

	void init(){
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			int checkPermission = this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
			if (checkPermission != PackageManager.PERMISSION_GRANTED) {
				requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
				return;
			}
		}

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
			// 适配android11读写权限
			if (Environment.isExternalStorageManager()) {
				//已获取android读写权限
			} else {
				Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
				intent.setData(Uri.parse("package:" + getPackageName()));
				startActivityForResult(intent, 1);
				return;
			}

		}

//		findViewById(R.id.tv1).setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View arg0) {
//				// TODO Auto-generated method stub
//				new UpdateApkTask().execute();
//
////				Intent i = new Intent(Intent.ACTION_VIEW);
////				if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
////					i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
////					Uri contentUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".fileprovider", new File(NEW_APK_PATH));
////					i.setDataAndType(contentUri, "application/vnd.android.package-archive");
////				}else {
////					i.setDataAndType(Uri.parse("file://" + NEW_APK_PATH), "application/vnd.android.package-archive");
////				}
////				startActivity(i);
//			}
//		});

		new UpdateApkTask().execute();


	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		Log.e("onActivityResult===", requestCode+"==="+data);

		switch (requestCode) {
			case 1:
				init();

				if (data != null) {
//                    starttime = data.getExtras().getString("starttime");
//                    endtime = data.getExtras().getString("endtime");
//					onRefresh();

				}
				break;

			default:
				break;
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		switch (requestCode) {
			case 0:
				if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					init();
				} else {
				}
				return;

			case 1:
				if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					init();
				} else {
				}
				return;

			default:
				super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		}
	}

	private class UpdateApkTask extends AsyncTask<String, Void, Integer> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
//			progressDialog.show();
		}

		@Override
		protected Integer doInBackground(String... params) {
			String oldApkSource = Utils.getSourceApkPath(context, getPackageName());

			Log.e("doInBackground===", "==="+oldApkSource);

			File file = new File(PATH,"myhotfix.patch");
			File newFile = new File(PATH,"new.apk");

			Log.e("doInBackground===1", file+"==="+file.exists()+"==="+newFile.exists());

//			return SUCCESS;
//			Utils.installApk(MainActivity.this, NEW_APK_PATH);

			if (!TextUtils.isEmpty(oldApkSource)) {
				int patchResult = -1;
				try {
					patchResult = BatchUtils.applyPatchToOwn(context, NEW_APK_PATH, PATCH_PATH);	//debug的apk不行，必须签名的apk

					Log.e("doInBackground===2", file+"==="+file.exists()+"==="+newFile.exists());
				} catch (IOException e) {

					e.printStackTrace();
				}
				if (patchResult == 0) {
//					String signatureNew = Utils.getUnInstalledApkSignature(NEW_APK_PATH);
//					String signatureSource = Utils.getInstalledApkSignature(MainActivity.this, getPackageName());
//					if (!TextUtils.isEmpty(signatureNew) && !TextUtils.isEmpty(signatureSource) && signatureNew.equals(signatureSource)) {
//						return SUCCESS;
//					} else {
//						return FAIL_SING;
//					}

					return SUCCESS;
				} else {
					return FAIL_ERROR;
				}
			} else {
				return FAIL_GET_SOURCE;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
//			if (progressDialog.isShowing()) {
//				progressDialog.dismiss();
//			}
			switch (result) {
				case SUCCESS:
//					showShortToast("新apk已合成成功：" + NEW_APK_PATH);
//					Utils.installApk(MainActivity.this, PATH + "SmartAppUpdate.apk");
//					Utils.installApk(context, NEW_APK_PATH);

//					RxAppTool.installApp(MainActivity.this, PATH + "SmartAppUpdate.apk");
//					RxAppTool.installApp(MainActivity.this, NEW_APK_PATH);

//					copy(new File(NEW_APK_PATH), "/data/data/com.fengmang.myapplication/new.apk");    //Y

					PluginManager.getInstance().loadPath2(context);

					Intent intent = new Intent(context, MainActivity.class);
					startActivity(intent);

					break;
				case FAIL_SING:
					showShortToast("新apk已合成失败，签名不一致");
					break;
				case FAIL_ERROR:
					showShortToast("新apk已合成失败");
					break;
				case FAIL_GET_SOURCE:
					showShortToast("无法获取packageName为" + getPackageName()
							+ "的源apk文件，只能整包更新了！");
					break;
			}
		}
	}

	private void showShortToast(final String text) {
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}


	public void copy(File oldPath, String newPath) {
		try {
			FileInputStream fileInputStream = new FileInputStream(oldPath);
			FileOutputStream fileOutputStream = new FileOutputStream(newPath);
			byte[] buffer = new byte[1024];
			int byteRead;
			while ((byteRead = fileInputStream.read(buffer)) != -1) {
				fileOutputStream.write(buffer, 0, byteRead);
			}

			Log.e("copy===", fileInputStream+"==="+fileOutputStream);

			fileInputStream.close();
			fileOutputStream.flush();
			fileOutputStream.close();
		} catch (Exception e) {
			Log.e("copy===e", "==="+e);
			e.printStackTrace();
		}
	}
}
